const conn = require('./db')

//查找
const selectInfor = (tableName) => {

    return new Promise((resolve, reject) => {
        conn.query(`select * from ${tableName}`, (err, results) => {
            if (err) {
                reject(err);
            } else {
                resolve(results);
            }
        })
    })
}
//添加
const insertInfo = (tableName, tableKeys, values) => {
    return new Promise((resolve, reject) => {
        // 插入数据
        let insertDataSql = `INSERT INTO ${tableName} (`;
        for (let i = 0; i < tableKeys.length; i++) {
            insertDataSql += `${tableKeys[i]}, `;
        }
        insertDataSql = insertDataSql.slice(0, -2); // Remove the last comma and space
        insertDataSql += `) VALUES ?`
        conn.query(insertDataSql, [values], (error, results) => {
            if (error) {
                reject(error);
            } else {
                resolve({ results: results, msg: "插入成功" });
            }
        });
    })
}

//查找表是否存在
const isHaveTable = (tableName) => {

    return new Promise((resolve, reject) => {
        conn.query(`SHOW TABLES LIKE "${tableName}"`, function (error, results) {
            if (error) {
                console.log(error)
                reject(error);
            } else {
                if (results.length === 0) {
                    resolve({ isHave: false, msg: "要创建表" });
                } else {
                    resolve({ isHave: true, msg: "表已存在" });
                }

            }
        })
    })
}

//创建表
const creatTable = (tableName, tableKeys) => {

    return new Promise((resolve, reject) => {
        let sql = `CREATE TABLE ${tableName} (${tableName}ID INT AUTO_INCREMENT PRIMARY KEY, `
        for (let i = 0; i < tableKeys.length; i++) {
            sql += `${tableKeys[i]} VARCHAR(255), `;
        }
        sql = sql.slice(0, -2); // Remove the last comma and space
        sql += ')';

        console.log("sql", sql)

        conn.query(sql, (err, results) => {
            if (err) {
                reject(err)
            } else {
                resolve({ results: results, msg: "表创建成功" })
            }
        })

    })

}

module.exports = {
    insertInfo,
    selectInfor,
    creatTable,
    isHaveTable,
}
